import moment from 'moment';
import {
  clearObject,
  deepCopyObj,
  floatDiv
} from '../../../assets/js/help.js';
import axios from 'axios'
export default {
  data() {
    var validateMoney = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('金额不能为空'));
      }
      if (value == 0) {
        return callback();
      }
      if (!/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/.test(value)) {
        return callback(new Error('请输入正确的金额'));
      } else {
        if (value < 0) {
          return callback(new Error('金额不能小于0'));
        } else {
          callback();
        }
      }
    };
    var validateTimeLength = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('时长不能为空'));
      }
      if (!/^[1-9]+[0-9]*$/.test(value)) {
        return callback(new Error('请输入大于0的数量'));
      }
      callback();
    };

    var validateTimeperiodListStr = (rule, value, callback) => {
      var self = this;
      if (self.modalData.mouthsSetting.monthsType == 'NATURAL_MONTH') {
        //自然月
        if (!self.monthShow || !self.monthShow.length) {
          return callback(new Error('请选择要开通的自然月'));
        }
      } else if (self.modalData.mouthsSetting.monthsType == 'CUSTOM') {
        //自定义
        if (!self.saveBill.timeperiodListStr || !self.saveBill.timeperiodListStr.length) {
          return callback(new Error('请选择要开通的日期范围'));
        }
      }
      callback();
    };
    var validateRealValue = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('折后价不能为空'));
      }
      if (value == 0) {
        return callback();
      }
      if (!/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/.test(value)) {
        return callback(new Error('请输入正确的金额'));
      } else {
        if (value < 0) {
          return callback(new Error('不能小于0'));
        } else {
          callback();
        }
      }
    };
    var validateCarCode = (rule, value, callback) => {
      /^([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领][a-zA-Z](([DF](?![a-zA-Z0-9]*[IO])[0-9]{4})|([0-9]{5}[DF])))|([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1})|民航[a-zA-Z0-9]{5}$/.test(
          value
        ) ?
        callback() :
        callback(new Error('车牌号格式不正确'));
    };
    return {
      placeholderText: '请选择',
      monthTicketConfigList_copy: [],
      editStatus: '', //月票编辑状态(new:新增;edit:编辑)
      canNotEdit: false, //不可编辑
      remarkChunkShow: false, //多个备注块是否显示
      Timer: null,
      bingCarNoList: [], //绑定车牌号的对象list
      defaultTime: 2 * 60 * 1000, //默认超时时间(2分钟)
      resyncMessageTimer: null, //读取同步结果信息定时器
      resyncMessage: [], //同步結果信息
      ifResync: true, //开启同步结果信息定时器标志
      qrImgUrl: '',
      cardNoBoxList: {
        weixin: [], //微信绑定
        writeCard: [], //绑卡
        hadCard: [] //已有卡
      },
      curWriteCardItem: null, //现在的写卡对象
      inviteCarList: [],
      inviteCarTable: {
        theadsInfo: [{
            index: 0,
            isShow: false,
            prop: 'reno',
            text: '序号',
            width: 68
          },
          {
            index: 1,
            isShow: false,
            prop: 'inviteTime',
            text: '邀请时间',
            minWidth: 150
          },
          {
            index: 2,
            isShow: false,
            prop: 'carCode',
            text: '车牌号',
            minWidth: 120
          }
        ]
      },
      minDate_: '',
      renewFormerDays_: 0,
      pickerOptions2: {
        shortcuts: [{
            text: '后一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '后一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '后三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '后一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      refundModel: {
        monthTicketBillId: '',
        refundValue: '',
        remark: ''
      },
      refundRules: {
        refundValue: [{
          validator: validateMoney,
          trigger: 'change'
        }],
        remark: [{
          max: 100,
          message: '最多100 个字符',
          trigger: 'change'
        }]
      },
      extendTimeModel: {
        monthTicketBillId: '',
        timeLength: ''
      },
      extendTimeRules: {
        timeLength: [{
          validator: validateTimeLength,
          trigger: 'change'
        }]
      },
      saveBill: {
        isShowTicketName: '', //是否展示月票类型名称下拉框
        moreInputCardCode: [], //多输入框车牌号填写
        isDynamicMode: '', // 是否多位多车（0否，1是）
        carCodeArr: '', //车牌号数组
        //  开通月票和续费传给后台的数据载体
        monthTicketId: '',
        monthTicketName: '',
        monthTicketBillId: '',
        timeperiodListStr: '',
        userName: '',
        userPhone: '',
        price: '',
        totalValue: '',
        openMonthNum: '',
        realValue: '',
        renewTimeLength: '',
        remark1: '',
        remark2: '',
        remark3: '',
        inviteCarTotal: 1,
        isDynamicMode: '', //是否多位多车（0否，1是）
        dynamicCarportNumber: 1,
        carCode: '', //车牌号
        cardCode: '' //备注卡号
      },
      editBill: {
        id: null,
        monthTicketId: null,
        monthTicketName: null,
        userName: null,
        userPhone: null,
        carCode: null,
        carCodeArr: [],
        remark1: '',
        remark2: '',
        remark3: '',
        dynamicCarportNumber: '', //可用车位数
        isDynamicMode: '' //是否多位多车（0否，1是）
      },
      billRules: {
        monthTicketId: [{
          required: true,
          message: '月票名称不能为空',
          trigger: 'change'
        }],
        userName: [{
            required: true,
            message: '车主姓名不能为空',
            trigger: 'change'
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'change'
          }
        ],
        userPhone: [{
            required: true,
            message: '购买手机号不能为空',
            trigger: 'change'
          },
          {
            validator(r, v, b) {
              /^1\d{10}$/.test(v) ? b() : b(new Error('手机格式不符合'));
            }
          }
        ],
        dynamicCarportNumber: [{
          required: true,
          message: '可用车位数不能为空',
          trigger: 'change'
        }],
        carCode: [{
            required: true,
            message: '车牌号不能为空',
            trigger: 'change'
          }
          // {
          //   validator(r, v, b) {
          //     /^([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领][a-zA-Z](([DF](?![a-zA-Z0-9]*[IO])[0-9]{4})|([0-9]{5}[DF])))|([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1})|民航[a-zA-Z0-9]{5}$/.test(
          //       v
          //     )
          //       ? b()
          //       : b(new Error('车牌号格式不正确'));
          //   }
          // }
        ],
        timeperiodListStr: [{
          required: true,
          validator: validateTimeperiodListStr,
          trigger: 'change'
        }],
        realValue: [{
            required: true,
            message: '折后价不能为空',
            trigger: 'change'
          },
          {
            validator: validateRealValue,
            trigger: 'change'
          }
        ],
        // renewTimeLength: [
        //   {
        //     validator: validateTimeLength,
        //     trigger: 'change'
        //   }
        // ],
        remark1: [{
          max: 50,
          message: '最多50个字符',
          trigger: ['blur', 'change']
        }],
        remark2: [{
          max: 50,
          message: '最多50个字符',
          trigger: ['blur', 'change']
        }],
        remark3: [{
          max: 50,
          message: '最多50个字符',
          trigger: ['blur', 'change']
        }]
      },
      monthTicketConfigList: [], //开通月票的配置列表
      modalData: {
        isOpenInnerTicket: 'YES',
        newText: '开通月票',
        renewalText: '续费',
        dataGet: '',
        mouthsSetting: {
          monthsType: '',
          placeholderText: '请选择日期'
        },
        supportVirtualCarcode: 0 //是否支持虚拟车牌(0:否;1:是)
      },
      monthShow: [], //显示选中的自然月
      naturalMonthData: {
        //自然月日历数据
        year: '',
        month: [
          ['一月', '二月', '三月', '四月'],
          ['五月', '六月', '七月', '八月'],
          ['九月', '十月', '十一月', '十二月']
        ]
      },
      yearN: '',
      monthN: '',
      alreadySelect: [],
      importResult: '',
      importFile: {
        importFile: ''
      },
      importRules: {},
      billModalTitle: '',
      renewBatchForm: {
        renewBatchFile: ''
      },
      renewBatchResult: '',
      batchRefundForm: {
        batchRefundFile: ''
      },
      batchRefundResult: '',
      // 解绑确认窗口对象
      unBindingCarCodeObj: {
        type: '', //类型(1:微信绑卡;2:开新卡;3:读旧卡)
        index: '', //数组索引
        carCode: '', //车牌
        cardCode: '' //备注卡号
      },
      // 已绑定车牌列表
      bindingCarCodeList: [],
      //需要解除与月票订单绑定关系的微信号
      openidsNeedUnbind: [],
      fileName: '', //上传文件名称
      fileList: [], //上传文件列表
      percentage: 10, //文件上传进度
      uploadFileTimer: null, //文件上传计时器
      uploadProgreeResult: '' //文件上传进度结果(1:进行中)
    };
  },
  watch: {
    // 开通月票-车牌号数组
    'saveBill.moreInputCardCode': function (value) {
      if (this.saveBill.isDynamicMode === 0) {
        //未开启多车多位
        this.saveBill.dynamicCarportNumber = value.length;
      }
    },
    // 编辑月票-车牌号数组
    'editBill.carCodeArr': function (value) {
      if (this.editBill.isDynamicMode === 0 && value.length > this.editBill.dynamicCarportNumber) {
        //未开启多车多位
        this.showToast('超过可用车位数，超位车牌请新开月票。', 0);
      }
    },
    // 新增and编辑
    'cardNoBoxList.weixin': function (value) {
      if (this.editStatus == 'new' && this.saveBill.isDynamicMode === 0) {
        //新增-未开启多车多位
        this.saveBill.dynamicCarportNumber =
          value.length + this.cardNoBoxList.writeCard.length + this.cardNoBoxList.hadCard.length;
        return;
      }
      if (this.editStatus == 'edit' && !this.canNotEdit && this.editBill.isDynamicMode === 0) {
        //可编辑and未开启多位多车
        let totalCount = 0;
        if (editBill.supportVirtualCarcode) {
          //支持虚拟车牌
          totalCount =
            this.cardNoBoxList.weixin.length + this.cardNoBoxList.writeCard.length + this.cardNoBoxList.hadCard.length;
        }
        if (totalCount > this.editBill.dynamicCarportNumber) {
          this.showToast('超过可用车位数，超位车牌请新开月票。', 0);
        }
      }
    },
    // 新增and编辑
    'cardNoBoxList.writeCard': function (value) {
      if (this.editStatus == 'new' && this.saveBill.isDynamicMode === 0) {
        //未开启多车多位
        this.saveBill.dynamicCarportNumber =
          value.length + this.cardNoBoxList.weixin.length + this.cardNoBoxList.hadCard.length;
        return;
      }
      if (this.editStatus == 'edit' && !this.canNotEdit && this.editBill.isDynamicMode === 0) {
        //可编辑and未开启多位多车
        let totalCount = 0;
        if (editBill.supportVirtualCarcode) {
          //支持虚拟车牌
          totalCount =
            this.cardNoBoxList.weixin.length + this.cardNoBoxList.writeCard.length + this.cardNoBoxList.hadCard.length;
        }
        if (totalCount > this.editBill.dynamicCarportNumber) {
          this.showToast('超过可用车位数，超位车牌请新开月票。', 0);
        }
      }
    },
    // 新增and编辑
    'cardNoBoxList.hadCard': function (value) {
      if (this.editStatus == 'new' && this.saveBill.isDynamicMode === 0) {
        //未开启多车多位
        this.saveBill.dynamicCarportNumber =
          value.length + this.cardNoBoxList.weixin.length + this.cardNoBoxList.writeCard.length;
        return;
      }
      if (this.editStatus == 'edit' && !this.canNotEdit && this.editBill.isDynamicMode === 0) {
        //可编辑and未开启多位多车
        let totalCount = 0;
        if (editBill.supportVirtualCarcode) {
          //支持虚拟车牌
          totalCount =
            this.cardNoBoxList.weixin.length + this.cardNoBoxList.writeCard.length + this.cardNoBoxList.hadCard.length;
        }
        if (totalCount > this.editBill.dynamicCarportNumber) {
          this.showToast('超过可用车位数，超位车牌请新开月票。', 0);
        }
      }
    },
    //计算自然月的总金额
    monthShow: function (value) {
      if (this.modalData.mouthsSetting.monthsType == 'CUSTOM') {
        //自定义
        return;
      }
      if (value.length !== 0) {
        this.saveBill.openMonthNum = value.length;
        this.saveBill.totalValue = (
          this.saveBill.price *
          this.saveBill.openMonthNum *
          this.saveBill.dynamicCarportNumber
        ).toFixed(2); //保留两位小数(四舍五入)
      } else {
        this.saveBill.openMonthNum = '';
        this.saveBill.totalValue = '';
      }
    },
    //计算自定义的总金额
    'saveBill.timeperiodListStr': function (value) {
      if (this.modalData.mouthsSetting.monthsType == 'NATURAL_MONTH') {
        //自然月
        return;
      }
      this.calculateTotalMoney2(value, this.saveBill);
    },
    // 车牌号
    'saveBill.moreInputCardCode': function (arr) {
      if (this.saveBill.isDynamicMode === 0) {
        this.saveBill.dynamicCarportNumber = arr.length;
      }
    },
    'saveBill.dynamicCarportNumber': function (value) {
      if (!this.saveBill.openMonthNum || !this.saveBill.dynamicCarportNumber) {
        this.saveBill.totalValue = '';
        this.saveBill.openMonthNum = '';
        return;
      }
      this.saveBill.totalValue = this.returnFloat(
        this.saveBill.price * this.saveBill.openMonthNum * this.saveBill.dynamicCarportNumber
      );
    }
  },
  created() {
    var self = this;
    self.yearN = this.yearNow();
    self.monthN = this.monthNow();
    self.startResyncMessageTimer();
    self.getTicketNameList();
    self.getMonthTicketList(); //开通月票弹框-月票类型下拉框
  },
  filters: {
    sendStatus: function (val) {
      switch (val) {
        case 'UNSEND':
          return '未发送';
        case 'SENDING':
          return '发送中';
        case 'FAILED':
          return '同步失败';
        case 'SUCCEED':
          return '同步成功';
        default:
          break;
      }
    }
  },
  filters: {
    sendStatus: function (value) {
      //value为优惠类型
      switch (value) {
        case 'FAILED':
          return '下发失败';
        case 'SUCCEED':
          return '下发成功';
        case 'SENDING':
          return '下发中';
        default:
          break;
      }
    },
    ticketType: function (value) {
      //value为优惠类型
      switch (value) {
        case 'INNER':
          return '本地月票';
        case 'OUTTER':
          return '线上月票';
        default:
          break;
      }
    },
    validStatus: function (value) {
      //value为优惠类型
      var val = Number(value);
      switch (val) {
        case 0:
          return '已付款';
        case 1:
          return '已退款';
        default:
          break;
      }
    },
    couponOrigin: function (value) {
      //value为优惠类型
      var val = Number(value);
      switch (val) {
        case 0:
          return '车场优惠';
        case 1:
          return '平台优惠';
        default:
          break;
      }
    }
  },
  methods: {
    moticketOptionsFocus() {
      this.placeholderText = '请选择/搜索月票类型/停车场'
      this.monthTicketConfigList = this.monthTicketConfigList_copy
    },
    filterMonthTicketOptions(val) {
      if (val) { //val存在
        this.monthTicketConfigList = this.monthTicketConfigList_copy.filter((item) => {
          if (item.ticketName.includes(val) || (item.parkNameList && item.parkNameList.find(item => item.includes(val)))) {
            return true;
          }
        })
      } else { //val为空时，还原数组
        this.monthTicketConfigList = this.monthTicketConfigList_copy;
      }
    },
    // 查看配置
    checkConfigure(rowData) {
      let params = {};
      params.id = rowData && rowData.monthTicketId ? rowData.monthTicketId : this.saveBill.monthTicketId;
      if (params.id !== 0 && !params.id) {
        this.showToast('请先选择月票类型', 0, 1500)
        return
      }
      this.$refs['monthTicketTypeComponent'].monthTicketTypeCheckFun(params);
    },
    // 获取月票名称列表
    getTicketNameList() {
      let self = this;
      let params = {}
      if(self.otherParams.hasOwnProperty(self.paramName) && self.otherParams[self.paramName]){
        params.parkIds = self.otherParams[self.paramName]
      }
      API.fetchGet('/commonFun/monthticket/findConfigNameList.do ', params).then(
        res => {
          let data = res.data ? res.data : [];
          let ticketNameList = [];
          ticketNameList.push({
            name: '--全部--',
            value: ''
          });
          for (let i = 0; i < data.length; i++) {
            ticketNameList.push({
              name: data[i],
              value: data[i]
            });
          }
          self.searchList[1].value = '';
          self.searchList[1].options = ticketNameList;
        },
        err => {}
      );
    },
    // 删除车牌号填写input框
    delCarCodeInput(idx, carCodeArr) {
      carCodeArr.splice(idx, 1);
    },
    // 创建新的月票类型
    addMonthTicketType() {
      this.$refs.monthTicketTypeComponent.createTicket2();
    },
    validateCarCode(rule, value, callback) {
      /^([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领][a-zA-Z](([DF](?![a-zA-Z0-9]*[IO])[0-9]{4})|([0-9]{5}[DF])))|([冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1})|民航[a-zA-Z0-9]{5}$/.test(
          value
        ) ?
        callback() :
        callback(new Error('车牌号格式不正确'));
    },
    // 增加车牌号填写框
    addCarCodeInput() {
      this.saveBill.moreInputCardCode.push({
        key: ''
      });
    },
    // 增加车牌号填写框--编辑
    addCarCodeInputForEdit() {
      this.editBill.carCodeArr.push({
        key: ''
      });
    },
    // 月票类型下拉选项
    configChange(val) {
      const item = this.monthTicketConfigList.find(item => item.id === val)
      this.saveBill.isShowTicketName = false;
      this.saveBill.monthTicketId = item.id;
      this.saveBill.monthTicketName = item.ticketName;
      this.saveBill.isDynamicMode = item.isDynamicMode; //是否支持多位多车（0否，1是）
      this.saveBill.price = item.renewMethod == 'CUSTOM' ? floatDiv(item.price, 30) : item.price; //单价
      this.modalData.supportVirtualCarcode = item.supportVirtualCarcode; //是否支持虚拟车牌
      this.modalData.mouthsSetting.monthsType = item.renewMethod; //续费方式
      if (item.renewMethod == 'CUSTOM') {
        //自定义
        this.calculateTotalMoney2(this.saveBill.timeperiodListStr, this.saveBill);
      } else {
        this.saveBill.openMonthNum = this.monthShow ? this.monthShow.length : ''; //开通月数
        this.saveBill.totalValue = (
          this.saveBill.price *
          this.saveBill.openMonthNum *
          this.saveBill.dynamicCarportNumber
        ).toFixed(2); //总价
      }
    },
    handleChange(file, fileList) {
      this.importFile.importFile = file.raw;
      this.fileName = file.raw.name;
    },
    // 查看已绑定的车牌号
    checkBindingCarCode(row, modalName) {
      let self = this;
      self.bindingCarCodeList = [];
      let params = {
        monthTicketBillId: row.id
      };
      API.fetchGet('monthTicketBill/getMonthTicketBillCarCodeDetail', params).then(
        res => {
          if (res.data) {
            let data = res.data;
            for (let i = 0; i < data.length; i++) {
              let obj = {
                carCode: data[i].logicCardCode //车牌
              };
              if (data[i].openid) {
                //微信
                obj.cardCode = data[i].nickname; //备注卡号
              } else {
                obj.cardCode = data[i].cardCode; //备注卡号
              }
              self.bindingCarCodeList.push(obj);
            }
          }
          self.toOpenModal(modalName);
        },
        err => {}
      );
    },
    // 解绑车牌
    unBindingCarCode(type, item) {
      let len =
        this.cardNoBoxList.weixin.length + this.cardNoBoxList.writeCard.length + this.cardNoBoxList.hadCard.length;
      if (len <= 1) {
        this.showToast('至少要绑定一个车牌', 0);
        return;
      }
      this.unBindingCarCodeObj.type = type;
      this.unBindingCarCodeObj.index = item.index;
      if (type == 1) {
        //微信
        this.unBindingCarCodeObj.carCode = item.carCode; //车牌
        this.unBindingCarCodeObj.cardCode = item.nickname; //微信称昵
      } else {
        this.unBindingCarCodeObj.carCode = item.carCode; //车牌
        this.unBindingCarCodeObj.cardCode = item.carNo; //备注卡号
      }
      this.toOpenModal('unBindingAskModal');
    },
    // 确定解绑车牌
    sureUnBindingCarCode() {
      let obj = {
        index: this.unBindingCarCodeObj.index
      };
      switch (this.unBindingCarCodeObj.type) {
        case 1:
          this.delCardBox(obj);
          break;
        case 2:
          this.delBindCardBox(obj);
          break;
        case 3:
          this.delReadOldCard(obj);
          break;
        default:
          break;
      }
      this.closed('unBindingAskModal');
    },
    //删除微信绑卡list-item
    delCardBox(item) {
      let objItem = this.cardNoBoxList.weixin[item.index];
      this.openidsNeedUnbind.push(objItem.openid);
      this.cardNoBoxList.weixin.splice(item.index, 1);
      this.cardNoBoxList.weixin.forEach((item, index) => {
        item.index = index;
      });
    },
    // 删除绑卡list-item
    delBindCardBox(item) {
      this.cardNoBoxList.writeCard.splice(item.index, 1);
      this.cardNoBoxList.writeCard.forEach((item, index) => {
        item.index = index;
      });
    },
    // 删除读旧卡list-item
    delReadOldCard(item) {
      this.cardNoBoxList.hadCard.splice(item.index, 1);
      this.cardNoBoxList.hadCard.forEach((item, index) => {
        item.index = index;
      });
    },
    // 读卡
    readOldCard() {
      let params = {
        block_no: 16
      };
      API.fetchGet('http://127.0.0.1:666/api/v1/card/block', params).then(
        res => {
          if (res.error_code == 0) {
            //读卡成功
            let data = res.data;
            let index = this.cardNoBoxList.hadCard.length;
            let obj = {
              index: index,
              carCode: '',
              canWriteCardNo: true,
              required: false,
              carNo: '' //逻辑卡号
            };
            API.fetchGet('/commonFun/card/decode.do', {
              ciphertext: data.data
            }).then(
              res => {
                if (res.status == 1) {
                  obj.carCode = res.data;
                  for (let i = 0; i < this.cardNoBoxList.hadCard.length; i++) {
                    let tempObj = this.cardNoBoxList.hadCard[i];
                    if (tempObj.carCode == obj.carCode) {
                      return;
                    }
                  }
                  for (let i = 0; i < this.cardNoBoxList.writeCard.length; i++) {
                    let tempObj = this.cardNoBoxList.writeCard[i];
                    if (tempObj.carCode == obj.carCode) {
                      return;
                    }
                  }
                  this.cardNoBoxList.hadCard.push(obj);
                  this.showToast('读卡成功并在车牌号输入框自动填入“该卡的逻辑卡号”', 1, 2000);
                }
              },
              err => {}
            );
          } else {
            switch (res.error_code) {
              case -1:
                this.showToast('请先连接好读卡器', 0, 2000);
                break;
              case -2:
                this.showToast('请先把卡放在读卡器上,然后点击[读卡]按钮读卡', 0, 2000);
                break;
              case -4:
                this.showToast('无法读取卡信息', 0, 2000);
                break;
            }
          }
        },
        err => {}
      );
    },
    // 绑卡-写卡
    writeCardOfBind(item) {
      let self = this;
      self.curWriteCardItem = item;
      let params = {
        logicCardCode: item.carCode
      };
      // 确认卡是否可写
      API.fetchPost('monthTicketBill/callWriteCard', params).then(
        res => {
          if (res.status == 1) {
            //可以写
            let aparams = {
              plaintext: item.carCode
            };
            // 加密
            API.fetchGet('commonFun/card/encode.do', aparams).then(
              res => {
                if (res.status == 1) {
                  this.realWriteCard(res.data, item.carCode);
                }
              },
              err => {}
            );
          }
        },
        err => {}
      );
    },
    // 写卡-把信息写入卡内
    realWriteCard(ciphertext, logicCardCode) {
      let params = {
        block_no: 16,
        data: ciphertext
      };
      API.fetchPost('http://127.0.0.1:666/api/v1/card/block', params).then(
        res => {
          if (res.error_code == 0) {
            //设备写卡成功
            API.fetchPost('monthTicketBill/writeCardCallback', {
              logicCardCode: logicCardCode
            }).then(
              res => {
                if (res.status == 1 && res.data) {
                  this.curWriteCardItem.isWriteCard = true;
                  this.showToast('写卡成功', 1, 2000);
                }
              },
              err => {}
            );
          } else {
            switch (res.error_code) {
              case -1:
                this.showToast('请先连接好读卡器', 0, 2000);
                break;
              case -2:
                this.showToast('请先把卡放在读卡器上,然后点击[写卡]按钮读卡', 0, 2000);
                break;
              case -5:
                this.showToast('写卡失败,请换一张空白卡再点击[写卡]重试', 0, 2000);
                break;
            }
          }
        },
        err => {}
      );
    },
    // 绑卡
    getBindCardCode() {
      let self = this;
      API.fetchPost('monthTicketBill/getCode', {}).then(
        res => {
          if (res.data) {
            let index = self.cardNoBoxList.writeCard.length;
            let obj = {
              index: index,
              carCode: res.data, //车牌号
              carNo: '', //卡号
              isWriteCard: false, //是否已进行写卡操作
              canWriteCardNo: true, //是否可以填写卡号
              required: false
            };
            self.cardNoBoxList.writeCard.push(obj);
          }
        },
        err => {}
      );
    },
    // 绑卡-保存备注卡号
    saveBingRemarkCardNo(item) {
      if (!item.carNo || item.carNo.length == 0) {
        item.required = true;
        return;
      }
      let params = {
        logicCardCode: item.carCode,
        cardCode: item.carNo
      };
      API.fetchPost('/monthTicketBill/writeCardRemark', params).then(
        res => {
          if (res.status == 1) {
            this.showToast('修改成功', 1);
            item.canWriteCardNo = false;
            item.required = false;
          }
        },
        err => {}
      );
    },
    // 读旧卡-保存备注卡号
    saveHadCardNo(item) {
      let params = {
        logicCardCode: item.carCode,
        cardCode: item.carNo
      };
      API.fetchPost('/monthTicketBill/writeCardRemark', params).then(
        res => {
          if (res.status == 1) {
            this.showToast('修改成功', 1);
            item.canWriteCardNo = false;
            item.required = false;
          }
        },
        err => {}
      );
    },
    //检测二维码是否已被扫描
    checkQrCodeIsScaned(item) {
      let self = this;
      if (!item) {
        return;
      }
      item.countTime += 2 * 1000;
      if (item.countTime >= self.defaultTime) {
        window.clearInterval(self.Timer);
        self.Timer = null;
        if (self.$refs['scanQrcodeModal'].show) {
          self.openScanQrModal(false);
        }
        return;
      }
      let params = {
        randomCode: item.randomCode
      };
      API.fetchPost('/monthTicketBill/checkScaned2', params).then(
        res => {
          if (res.data) {
            window.clearInterval(self.Timer);
            self.Timer = null;
            self.bingCarNoList.splice(item.index, 1);
            let data = res.data;
            let index = self.cardNoBoxList.weixin.length;
            let obj = {
              index: index,
              nickname: data.nickname,
              carCode: data.carCode,
              openid: data.openid
            };
            for (let i = 0; i < self.cardNoBoxList.weixin.length; i++) {
              let objItem = self.cardNoBoxList.weixin[i];
              if (objItem.openid == obj.openid) {
                self.closed('scanQrcodeModal');
                return;
              }
            }
            self.cardNoBoxList.weixin.push(obj);
            self.closed('scanQrcodeModal');
          }
        },
        err => {}
      );
    },
    // 打开二维码扫描弹窗
    openScanQrModal(flag) {
      let self = this;
      API.fetchPost('monthTicketBill/getRandomCode', {}).then(
        res => {
          if (res.data) {
            let uri =
              window.location.href.split('/?')[0] +
              '/mgr/monthTicketBill/generateQrGetWechatCarCode.do?' +
              'randomCode=' +
              res.data;
            let index = self.bingCarNoList.length;
            let objItem = {
              index: index,
              Timer: null,
              countTime: 0,
              randomCode: res.data
            };
            self.bingCarNoList.push(objItem);
            window.clearInterval(self.Timer);
            self.Timer = null;
            self.Timer = window.setInterval(function () {
              self.checkQrCodeIsScaned(self.bingCarNoList[index]);
            }, 2 * 1000);
            self.qrImgUrl = uri;
            if (flag) {
              self.toOpenModal('scanQrcodeModal');
            }
          }
        },
        err => {}
      );
    },
    timeChange(billObj) {
      billObj.timeperiodListStr = [
        new Date(moment(billObj.timeperiodListStr[0]).format('YYYY-MM-DD 00:00:00')),
        new Date(moment(billObj.timeperiodListStr[1]).format('YYYY-MM-DD 23:59:59'))
      ];
    },
    computeVal() {
      if (!this.saveBill.openMonthNum || !this.saveBill.dynamicCarportNumber) {
        this.saveBill.totalValue = '';
        this.saveBill.openMonthNum = '';
        return;
      }
      this.saveBill.totalValue = this.returnFloat(
        this.saveBill.price * this.saveBill.openMonthNum * this.saveBill.dynamicCarportNumber
      );
    },
    returnFloat(value) {
      var value = Math.round(parseFloat(value) * 100) / 100;
      var xsd = value.toString().split('.');
      if (xsd.length == 1) {
        value = value.toString() + '.00';
        return value;
      }
      if (xsd.length > 1) {
        if (xsd[1].length < 2) {
          value = value.toString() + '0';
        }
        return value;
      }
    },
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      if (params.hasOwnProperty('query_carCode')) {
        delete params.query_carCode;
        let attribStr = this.searchList[0].value;
        params[attribStr] = this.searchList[0].inputVal;
      }
      for(let key in params){
        if(params.hasOwnProperty(key) && (params[key]==='' || params[key]===null)){
          delete params[key]
        }
      }
      if(params){
        for(let key in params){
          if(params.hasOwnProperty(key) && !params[key]){
            delete params[key]
          }
        }
      }
      this.list(params);
    },
    list(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.monthTicket.billList(params).then(
        res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        },
        err => {}
      );
    },
    toResyncBill(bill) {
      let self = this;
      self.id = bill.id;
      self.ticketCode = bill.ticketCode;
      self.toOpenModal('billResyncModal');
    },
    submitBillResyncForm() {
      let self = this;
      let params = {
        monthTicketBillId: self.id,
        ticketCode: self.ticketCode
      };
      API.fetchPost('/monthTicketBill/resync.do', params);
      self.closed('billResyncModal');
      self.startResyncMessageTimer();
      self.getList();
    },
    toRefund(bill) {
      let self = this;
      clearObject(self.refundModel); //清空属性
      self.refundModel.monthTicketBillId = bill.id;
      self.refundModel.realValue = ((bill.totalValue - bill.reliefValue) * 100).toFixed(0);
      self.toOpenModal('refundModal');
    },

    submitRefundForm() {
      var self = this;
      this.$refs['refundForm'].validate(valid => {
        if (valid) {
          self.refund();
        } else {
          return false;
        }
      });
    },
    refund() {
      var self = this;
      if (self.refundModel.realValue < self.refundModel.refundValue * 100) {
        self.showToast('退款金额不能大于实付金额', 0);
        return false;
      }
      var params = deepCopyObj(self.refundModel);
      API.monthTicket.billRefund(params).then(
        res => {
          var data = res;
          if (data.status == 1) {
            self.showToast('退款成功', 1);
            self.closed('refundModal');
            self.getList();
          }
        },
        err => {}
      );
    },
    toExtendTime(bill) {
      let self = this;
      clearObject(self.extendTimeModel); //清空属性
      self.extendTimeModel.monthTicketBillId = bill.id;
      self.toOpenModal('extendTimeModal');
    },
    submitExtendTimeForm() {
      var self = this;
      this.$refs['extendTimeForm'].validate(valid => {
        if (valid) {
          self.extendTime();
        } else {
          return false;
        }
      });
    },
    extendTime() {
      var self = this;
      var params = deepCopyObj(self.extendTimeModel);
      API.monthTicket.billExtendTime(params).then(
        res => {
          var data = res;
          if (data.status == 1) {
            self.showToast('延长成功', 1);
            self.closed('extendTimeModal');
            self.getList();
          }
        },
        err => {}
      );
    },
    openInnerTiket() {
      var self = this;
      self.minDate_ = '';
      self.billModalTitle = '开通月票';
      self.remarkChunkShow = false;
      clearObject(self.saveBill);
      self.resetDate();
      // 清空邦卡数据-start
      self.cardNoBoxList.weixin = [];
      self.cardNoBoxList.writeCard = [];
      self.cardNoBoxList.hadCard = [];
      // 清空邦卡数据-end
      self.editStatus = 'new'; //新增
      self.saveBill.dynamicCarportNumber = 1;
      self.modalData.isOpenInnerTicket = 'YES';
      self.modalData.supportVirtualCarcode = 0; //是否支持虚拟车牌
      self.naturalMonthData.year = self.yearNow();
      API.monthTicket.billValidInnerConfigList({}).then(
        res => {
          var data = res;
          if (data.status == 1) {
            if (data.data && data.data.length > 0) {
              self.monthTicketConfigList = data.data;
              self.monthTicketConfigList_copy = JSON.parse(JSON.stringify(data.data))
              self.saveBill.monthTicketName = self.monthTicketConfigList[0]['ticketName'];
              self.saveBill.isDynamicMode = self.monthTicketConfigList[0]['isDynamicMode']; //是否支持多位多车
              self.modalData.mouthsSetting.monthsType = self.monthTicketConfigList[0]['renewMethod'];
              self.modalData.supportVirtualCarcode = self.monthTicketConfigList[0]['supportVirtualCarcode']; //是否支持虚拟车牌
              self.saveBill.price =
                self.modalData.mouthsSetting.monthsType == 'CUSTOM' ?
                floatDiv(self.monthTicketConfigList[0]['price'], 30) :
                self.monthTicketConfigList[0]['price'];
              self.saveBill.totalValue = ''; //总价
            } else {
              self.placeholderText = '请先创建月票类型'
            }
            self.toOpenModal('billModal');
          }
        },
        err => {}
      );
    },
    // 获取开通月票-月票名称下拉框
    getMonthTicketList(id) {
      let self = this;
      API.monthTicket.billValidInnerConfigList({}).then(
        res => {
          var data = res;
          if (data.status == 1) {
            if (data.data && data.data.length > 0) {
              self.monthTicketConfigList = data.data;
              if(id){
                self.configChange(id)
              }
            }
          }
        },
        err => {}
      );
    },
    // 选择月票类型
    changeMonthTicketId(item) {
      this.editBill.monthTicketId = item.id;
      this.editBill.monthTicketName = item.ticketName;
      this.editBill.supportVirtualCarcode = item.supportVirtualCarcode;
    },
    toEdit(bill) {
      var self = this;
      // 清空邦卡数据-start
      self.cardNoBoxList.weixin = [];
      self.cardNoBoxList.writeCard = [];
      self.cardNoBoxList.hadCard = [];
      // 清空邦卡数据-end
      self.openidsNeedUnbind = [];
      clearObject(self.editBill);
      self.editBill.id = bill.id;
      self.editBill.monthTicketId = bill.monthTicketId;
      self.editBill.userPhone = bill.userPhone;
      self.editBill.monthTicketName = bill.ticketName;
      self.editBill.isDynamicMode = ''; //开启多车多位
      self.editBill.carCodeArr = [];
      self.editBill.carCode = bill.carCode;
      self.editBill.remark1 = bill.remark1;
      self.editBill.remark2 = bill.remark2;
      self.editBill.remark3 = bill.remark3;
      if (bill.parkSysType == 1) {
        //非vems车场
        self.canNotEdit = false;
        self.getIsDynamicMode(bill.id); //是否开启多位多车(0:未开启;1:开启)
      } else {
        //vems车场
        self.canNotEdit = true; //不可编辑
        self.checkVemsVersion(bill.id);
      }
      self.editBill.userName = bill.userName;
      self.editBill.supportVirtualCarcode = bill.supportVirtualCarcode;
      self.editBill.dynamicCarportNumber = bill.dynamicCarportNumber; //可用车位数
      if (bill.supportVirtualCarcode) {
        //电动车
        self.getEleCarInfo(bill.id);
      } else {
        if (bill.carCode) {
          let carCodeArr = bill.carCode.split(',');
          for (let i = 0; i < carCodeArr.length; i++) {
            self.editBill.carCodeArr.push({
              key: carCodeArr[i]
            });
          }
        }
      }
      self.toOpenModal('billEditModal');
    },
    // 针对vems车场检测版本是否是3.0版本
    checkVemsVersion(id) {
      let self = this;
      let params = {
        id: id
      };
      API.fetchGet('/monthTicketBill/checkEdit.do', params).then(
        res => {
          if (res.data) {
            self.canNotEdit = !res.data.edit;
            if (res.data.edit === true) {
              //可编辑
              self.getIsDynamicMode(id); //是否开启多位多车(0:未开启;1:开启)
            }
          }
        },
        err => {}
      );
    },
    // 编辑状态下获取是否开启多位多车(0:未开启;1:开启)
    getIsDynamicMode(id) {
      let self = this;
      let params = {
        id: id
      };
      return API.fetchGet('/monthTicketBill/checkMonthTicketBillIsDynamicMode.do', params).then(
        res => {
          if (res.data) {
            self.editBill.isDynamicMode = res.data.isDynamicMode;
          }
        },
        err => {}
      );
    },
    toRenew(bill) {
      var self = this;
      self.billModalTitle = '续费月票';
      self.remarkChunkShow = false;
      self.modalData.isOpenInnerTicket = 'NO';
      clearObject(self.saveBill);
      self.saveBill.monthTicketId = bill.monthTicketId;
      self.saveBill.monthTicketName = bill.ticketName;
      self.saveBill.monthTicketBillId = bill.id;
      self.saveBill.userName = bill.userName;
      self.saveBill.userPhone = bill.userPhone;
      self.saveBill.price = bill.renewMethod == 'CUSTOM' ? floatDiv(bill.price, 30) : bill.price; //单价
      self.saveBill.dynamicCarportNumber = bill.dynamicCarportNumber; //可用车位数
      self.saveBill.carCodeArr = bill.carCode ? bill.carCode.split(',') : []; //车牌号
      self.saveBill.remark1 = bill.remark1;
      self.saveBill.remark2 = bill.remark2;
      self.saveBill.remark3 = bill.remark3;
      self.modalData.mouthsSetting.monthsType = bill.renewMethod; //续费方式
      self.modalData.supportVirtualCarcode = null; //是否支持虚拟车牌
      // 2017-10-01至2017-10-31,2017-11-01至2017-12-31  数据模板
      var mouthArr = bill.timeperiodList.split(',');
      var mouthArr1 = [];
      for (var i = 0; i < mouthArr.length; i++) {
        var mouthStr = mouthArr[i].split('至')[1];
        mouthArr1.push(mouthStr);
      }
      mouthArr1.sort(function (a, b) {
        return a > b ? 1 : -1;
      });
      var currentdata = mouthArr1[mouthArr1.length - 1];
      if (bill.renewMethod == 'CUSTOM') {
        //自定义日期
        var nextDay =
          moment(currentdata)
          .add(1, 'days')
          .format('YYYY-MM-DD') +
          ' ' +
          '00:00:00';
        var monthAdd =
          moment(currentdata)
          .add(30, 'days')
          .format('YYYY-MM-DD') +
          ' ' +
          '23:59:59';

        self.saveBill.timeperiodListStr = [new Date(nextDay), new Date(monthAdd)]; //vue赋值-自定义月份

        //月票续费-自定义日期时，设置可选的最少日期
        var nowDayDate = moment()
          .add(-bill.renewFormerDays, 'days')
          .format('YYYY-MM-DD 00:00:00');
        self.renewFormerDays_ = bill.renewFormerDays;
        self.minDate_ = self.getMinDate(new Date(nextDay), new Date(nowDayDate));
        //重新赋值
        nextDay = self.minDate_.Format('yyyy-MM-dd') + ' ' + '00:00:00';
        monthAdd =
          moment(nextDay)
          .add(29, 'days')
          .format('YYYY-MM-DD') +
          ' ' +
          '23:59:59';
        self.saveBill.timeperiodListStr = [new Date(nextDay), new Date(monthAdd)]; //vue赋值-自定义月份
        self.saveBill.openMonthNum = 30; //续费天数
        self.saveBill.totalValue =
          (self.saveBill.price * self.saveBill.openMonthNum * self.saveBill.dynamicCarportNumber) >> 0; //总价
      } else if (bill.renewMethod == 'NATURAL_MONTH') {
        //自然月
        // 编辑时显示不能续费的月份为灰色
        if (bill.timeperiodList) {
          self.alreadySelect = self.seriesMonth(bill.timeperiodList);
        } else {
          self.alreadySelect = [];
        }

        currentdata = self.getNextMonth(currentdata) + ' ' + '23:59:59';
        var pp3 = moment(currentdata, 'YYYY-MM')
          .endOf('month')
          .format('YYYY-MM');
        self.monthShow = [];
        self.monthShow.push(pp3);
        self.naturalMonthData.year = pp3.split('-')[0];
        self.saveBill.openMonthNum = 1; //续费月数
        self.saveBill.totalValue = (
          self.saveBill.price *
          self.saveBill.openMonthNum *
          self.saveBill.dynamicCarportNumber
        ).toFixed(2); //总价
      }
      self.toOpenModal('renewbillModal');
    },
    // 弹框获取电动车信息
    getEleCarInfo(id) {
      let self = this;
      let params = {
        monthTicketBillId: id
      };
      API.fetchGet('monthTicketBill/getMonthTicketBillCarCodeDetail', params).then(
        res => {
          if (res.data) {
            let data = res.data;
            for (let i = 0; i < data.length; i++) {
              let obj = {
                carCode: data[i].logicCardCode //车牌
              };
              if (data[i].openid) {
                obj.openid = data[i].openid;
                obj.index = self.cardNoBoxList.weixin.length;
                obj.nickname = data[i].nickname;
                self.cardNoBoxList.weixin.push(obj);
              } else {
                obj.index = self.cardNoBoxList.writeCard.length;
                obj.carNo = data[i].cardCode; //备注卡号
                obj.canWriteCardNo = false; //是否可以填写备注卡号
                obj.isWriteCard = data[i].writeTimes ? true : false; //是否已进行写卡操作
                obj.required = false;
                self.cardNoBoxList.writeCard.push(obj);
              }
            }
          }
        },
        err => {}
      );
    },
    getMinDate(nextDayDate, nowDayDate) {
      var nextDayDateTime = nextDayDate.getTime();
      var nowDayDateTime = nowDayDate.getTime();
      if (nextDayDateTime <= nowDayDateTime) {
        return nowDayDate;
      } else {
        return nextDayDate;
      }
    },
    // 月票续费-提交
    submitRenewBillForm(formName) {
      let self = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          self.saveBillForm('renewbillModal'); //保存月票续费数据
        } else {
          return false;
        }
      });
    },
    // 月票编辑-提交
    submitBillEditForm() {
      var self = this;
      if (!self.editBill.supportVirtualCarcode) {
        //不支持电动车
        let carCodeArr = [];
        for (let i = 0; i < self.editBill.carCodeArr.length; i++) {
          let obj = self.editBill.carCodeArr[i];
          if (obj.key) {
            carCodeArr.push(obj.key);
          }
        }
        self.editBill.carCode = carCodeArr.join(',');
        if (!self.editBill.carCode) {
          self.showToast('请填写车牌号', 0);
          return;
        }
        if (self.editBill.isDynamicMode === 0 && carCodeArr.length > self.editBill.dynamicCarportNumber) {
          //未开启多位多车
          self.showToast('超过可用车位数，超位车牌请新开月票。', 0);
          return;
        }
      }
      this.$refs['billEditForm'].validate(valid => {
        if (valid) {
          self.editBillForm();
        } else {
          return false;
        }
      });
    },
    editBillForm() {
      var self = this;
      if (self.editBill.supportVirtualCarcode) {
        if (!self.arrangeCarCodeAndCardNo(self.editBill)) {
          return;
        }
        if (!self.editBill.carCode) {
          self.showToast('至少绑定一个车牌', 0);
          return;
        }
        let carCodeArr = self.editBill.carCode.split(',');
        if (self.editBill.isDynamicMode === 0 && carCodeArr.length > self.editBill.dynamicCarportNumber) {
          //未开启多位多车
          self.showToast('超过可用车位数，超位车牌请新开月票。', 0);
          return;
        }
        self.editBill.openidsNeedUnbind = self.openidsNeedUnbind.join(',');
      }

      var param = deepCopyObj(self.editBill);
      delete param.carCodeArr;
      API.fetchPost('/monthTicketBill/preeditMonthTicketBill.do', param).then(
        res => {
          if (res.status === 1) {
            API.monthTicket.billEdit(param).then(
              res => {
                var data = res;
                if (data.status == 1) {
                  self.closed('billEditModal');
                  self.showToast('操作成功', 1);
                  self.getList();
                } else {
                  self.showToast('操作失败', 2);
                }
              },
              err => {}
            );
          }
        },
        err => {}
      );
    },
    submitBillForm() {
      var self = this;
      if (self.modalData.supportVirtualCarcode) {
        //支持虚拟车牌
        self.saveBill.carCode = '粤EJW962'; //为了跳过表单验证
      } else {
        let carCodeArr = [];
        for (let i = 0; i < self.saveBill.moreInputCardCode.length; i++) {
          let obj = self.saveBill.moreInputCardCode[i];
          if (obj.key) {
            carCodeArr.push(obj.key);
          }
        }
        self.saveBill.carCode = carCodeArr.join(',');
        if (!self.saveBill.carCode) {
          self.showToast('请填写车牌号', 0);
          return;
        }
      }
      this.$refs['billForm'].validate(valid => {
        if (valid) {
          self.saveBillForm('billModal');
        } else {
          return false;
        }
      });
    },
    // 电动车-整理车牌和备注卡号
    arrangeCarCodeAndCardNo(saveBill) {
      let self = this;
      let carCodeArr = [],
        cardCodeArr = []; //车牌号,备注卡号
      for (let i = 0; i < self.cardNoBoxList.weixin.length; i++) {
        let obj = self.cardNoBoxList.weixin[i];
        carCodeArr.push(obj.carCode);
        cardCodeArr.push('');
      }
      // 开新卡-检测是否有填写备注卡号
      for (let i = 0; i < self.cardNoBoxList.writeCard.length; i++) {
        let obj = self.cardNoBoxList.writeCard[i];
        if (!obj.carNo) {
          obj.required = true;
          return false;
        }
        obj.required = false;
        carCodeArr.push(obj.carCode);
        cardCodeArr.push(obj.carNo);
      }
      // 读旧卡-检测是否有填写备注卡号
      for (let i = 0; i < self.cardNoBoxList.hadCard.length; i++) {
        let obj = self.cardNoBoxList.hadCard[i];
        if (!obj.carNo) {
          obj.required = true;
          return false;
        }
        obj.required = false;
        carCodeArr.push(obj.carCode);
        cardCodeArr.push(obj.carNo);
      }
      saveBill.carCode = carCodeArr.join(',');
      saveBill.cardCode = cardCodeArr.join(',');
      return true;
    },
    saveBillForm(modalName) {
      var self = this;
      // 支持电动车
      if (self.modalData.supportVirtualCarcode) {
        if (!self.arrangeCarCodeAndCardNo(self.saveBill)) {
          return;
        }
        if (!self.saveBill.carCode) {
          self.showToast('至少绑定一个车牌', 0);
          return;
        }
      }
      var arr = [];
      //获取表单对象
      var param = deepCopyObj(self.saveBill);
      if (self.modalData.mouthsSetting.monthsType == 'NATURAL_MONTH') {
        //自然月
        var mouths = self.sortMonth(self.monthShow);
        for (var i = 0; i < mouths.length; i++) {
          let m1 = mouths[i].split('~')[0];
          let m2 = mouths[i].split('~')[1];
          var pp1 = moment(m1, 'YYYY-MM')
            .startOf('month')
            .format('YYYY-MM-DD HH:mm:ss');
          var pp2 = moment(m2, 'YYYY-MM')
            .endOf('month')
            .format('YYYY-MM-DD HH:mm:ss');
          arr.push(pp1 + ' - ' + pp2);
        }
      } else {
        //自定义
        if (typeof self.saveBill.timeperiodListStr[0] == 'object') {
          arr.push(
            moment(self.saveBill.timeperiodListStr[0]).format('YYYY-MM-DD HH:mm:ss') +
            ' - ' +
            moment(self.saveBill.timeperiodListStr[1]).format('YYYY-MM-DD 23:59:59')
          );
        } else {
          arr.push(self.saveBill.timeperiodListStr[0] + ' - ' + self.saveBill.timeperiodListStr[1]);
        }
      }
      param.timeperiodListStr = arr.join(',');
      if (param.timeperiodListStr == '') {
        self.showToast('请选择有效日期', 2);
        return;
      }
      delete param.moreInputCardCode;
      delete param.isShowTicketName;
      delete param.isDynamicMode;
      delete param.carCodeArr;
      if (self.modalData.isOpenInnerTicket == 'NO') {
        API.monthTicket.billRenew(param).then(
          res => {
            //start
            var data = res;
            if (data.status == 1) {
              self.showToast('操作成功', 1);
              self.closed(modalName);
              self.getList();
            }
            //end
          },
          err => {}
        );
      } else {
        API.monthTicket.billOpen(param).then(
          res => {
            //start
            var data = res;
            if (data.status == 1) {
              self.showToast('操作成功', 1);
              self.closed(modalName);
              self.getList();
            }
            //end
          },
          err => {}
        );
      }
    },
    innerTiketChange(id) {
      this.resetDate();
      var arr = id.split(',');
      var index = Number(arr[1]);
      this.modalData.supportVirtualCarcode = this.monthTicketConfigList[index]['supportVirtualCarcode'];
      this.saveBill.price = this.monthTicketConfigList[index]['price'];
      this.modalData.mouthsSetting.monthsType = this.monthTicketConfigList[index]['renewMethod'];
    },
    resetDate() {
      var self = this;
      self.monthShow = [];
      self.alreadySelect = [];
      self.saveBill.moreInputCardCode = [{
        key: ''
      }];
      self.saveBill.timeperiodListStr = '';
      self.saveBill.totalValue = '';
      self.saveBill.openMonthNum = '';
      self.saveBill.inviteCarTotal = 1;
      self.saveBill.carCode = ''; //车牌号
      self.saveBill.cardCode = ''; //卡号
      self.saveBillForm.isDynamicMode = ''; //是否开启多位多车
    },
    cut() {
      var yearNow = this.yearNow();
      if (this.naturalMonthData.year == yearNow) {
        return;
      } else {
        this.naturalMonthData.year--;
      }
    },
    add() {
      this.naturalMonthData.year++;
    },
    del(index) {
      this.monthShow.splice(index, 1);
    },
    getMonth(index, tt) {
      var yearNow = this.yearNow();
      var monthNow = this.monthNow();
      var month = index + 1 + tt * 4 >= 10 ? index + 1 + tt * 4 : '0' + (index + 1 + tt * 4);
      if (this.naturalMonthData.year == yearNow) {
        if (month < monthNow) {
          return;
        }
      }
      var date = this.naturalMonthData.year + '-' + month;
      if (this.monthShow.length == 0) {
        this.monthShow.push(date);
        return;
      } else {
        for (var i = 0; i < this.monthShow.length; i++) {
          if (this.monthShow[i] == date) {
            this.monthShow.splice(i, 1);
            return;
          }
        }
        for (var i = 0; i < this.alreadySelect.length; i++) {
          if (this.alreadySelect[i] == date) {
            return;
          }
        }
      }
      this.monthShow.push(date);
    },
    yearNow() {
      var dt = new Date();
      return dt.getFullYear(); //获取年(四位)   用于判断日历不能选择今天之前的月份
    },
    monthNow() {
      var dt = new Date();
      return dt.getMonth() + 1; //获取月份   用于判断日历不能选择今天之前的月份
    },
    resetInit() {
      var self = this;
      clearObject(self.saveBill);
    },
    getNextDay(d) {
      d = new Date(d);
      d = +d + 1000 * 60 * 60 * 24;
      d = new Date(d);
      //return d;
      //格式化
      return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    },
    getNextMonth(date) {
      var nextMonth;
      var nextday = this.getNextDay(date);
      var nextdayArr = nextday.split('-');
      var year = Number(nextdayArr[0]); //获取当前日期的年份
      var month = Number(nextdayArr[1]); //获取当前日期的月份
      var day = Number(nextdayArr[2]); //获取当前日期的日
      var days = new Date(year, month, 0).getDate(); //获取当前日期中的月的天数
      if (month == 1 && (day == 30 || day == 31 || day == 29)) {
        nextMonth = year + '-' + '02' + '-' + (year % 4 == 0 ? '29' : '28');
        return nextMonth;
      } else if (day == 1) {
        nextMonth = year + '-' + (month > 9 ? month : '0' + month) + '-' + days;
        return nextMonth;
      } else if (month == 12) {
        nextMonth = year + 1 + '-' + '01' + '-' + (day - 1 > 9 ? day - 1 > 9 : '0' + (day - 1));
        return nextMonth;
      } else {
        nextMonth =
          year +
          '-' +
          (month + 1 > 9 ? month + 1 : '0' + (month + 1)) +
          '-' +
          (day - 1 > 9 ? day - 1 : '0' + (day - 1));
        return nextMonth;
      }
    },
    seriesMonth(params) {
      var str = params || '2017-02-01至2017-07-31,2017-09-01至2018-10-31,2019-11-01至2021-11-28';
      var arr = str.split(',');
      var newarr = [];
      arr.forEach(function (element) {
        var dateA = element.split('至')[0];
        var dateB = element.split('至')[1];
        var number;
        var dateA_Y = dateA.split('-')[0];
        var dateA_M = dateA.split('-')[1];
        var dateA_D = dateA.split('-')[2];
        var dateB_Y = dateB.split('-')[0];
        var dateB_M = dateB.split('-')[1];
        var dateB_D = dateB.split('-')[2];
        // console.log('dateA_Y, dateA_M, dateB_Y, dateB_M', dateA_Y, dateA_M, dateB_Y, dateB_M)
        // 年份相等
        if (Number(dateA_Y) == Number(dateB_Y)) {
          for (var index = 0; Number(dateA_M) + index <= Number(dateB_M); index++) {
            newarr.push(
              Number(dateA_Y) +
              '-' +
              (Number(dateA_M) + index >= 10 ? Number(dateA_M) + index : '0' + (Number(dateA_M) + index))
            );
          }
        }

        // 年份不相等
        if (Number(dateA_Y) !== Number(dateB_Y)) {
          number = Number(dateB_Y) * 12 + Number(dateB_M) - (Number(dateA_Y) * 12 + Number(dateA_M)) + 1;
          var number_Y = Number(dateB_Y) - Number(dateA_Y) - 1;

          for (var index = 0; Number(dateA_M) + index <= 12; index++) {
            newarr.push(
              Number(dateA_Y) +
              '-' +
              (Number(dateA_M) + index >= 10 ? Number(dateA_M) + index : '0' + (Number(dateA_M) + index))
            );
          }

          if (number_Y > 0) {
            for (var yy = 1; yy <= number_Y; yy++) {
              for (var index = 1; index <= 12; index++) {
                newarr.push(Number(dateA_Y) + yy + '-' + (index >= 10 ? index : '0' + index));
              }
            }
          }

          for (var index = 1; index <= dateB_M; index++) {
            newarr.push(Number(dateB_Y) + '-' + (index >= 10 ? index : '0' + index));
          }
        }
      }, this);
      return newarr;
    },
    sortMonth(monthArr) {
      monthArr.sort(function (a, b) {
        var aArr = a.split('-');
        var bArr = b.split('-');
        //判断年份
        if (aArr[0] > bArr[0]) {
          return 1;
        }
        if (aArr[0] < bArr[0]) {
          return -1;
        }

        //年份相等判断月份
        if (parseInt(aArr[1]) > parseInt(bArr[1])) {
          return 1;
        } else {
          return -1;
        }
      }); //排序完毕

      function isContinuous(a, b) {
        var aArr = a.split('-');
        var bArr = b.split('-');
        if (parseInt(aArr[0]) == parseInt(bArr[0]) && parseInt(aArr[1]) + 1 == parseInt(bArr[1])) {
          return true;
        }
        if (parseInt(aArr[0]) + 1 == parseInt(bArr[0]) && parseInt(aArr[1]) == 12 && parseInt(bArr[1]) == 1) {
          return true;
        }
        return false;
      }

      function merge(a, b) {
        return a + '~' + b;
      }

      var newMonthArray = [];
      for (var i = 0; i < monthArr.length; i++) {
        if (newMonthArray.length == 0) {
          newMonthArray.push(monthArr[i] + '~' + monthArr[i]);
          continue;
        }
        if (isContinuous(newMonthArray[newMonthArray.length - 1].split('~')[1], monthArr[i])) {
          newMonthArray[newMonthArray.length - 1] =
            newMonthArray[newMonthArray.length - 1].split('~')[0] + '~' + monthArr[i];
        } else {
          newMonthArray.push(monthArr[i] + '~' + monthArr[i]);
        }
      }
      return newMonthArray;
    },
    async importData() {
      var self = this;
      self.importResult = {};
      self.importFile.importFile = '';
      self.fileName = '';
      self.uploadProgreeResult = '';
      self.percentage = 10;
      self.tabIndex = 1;
      await self.getLastTimeImportResult();
      self.dialogVisible = true;
    },
    // 批量开通-获取上一次的导入结果(成功or失败)
    getLastTimeImportResult(){
      let self = this
      return API.fetchGet('/monthTicketBill/getImportBillResult.do',{}).then(result=>{
        if (result.status == 1) {
          self.importResult = result.data;
          if (self.importResult && self.importResult.successCount==self.importResult.totalCount) {
            self.importResult.successCount=0;
          }
        }
      })
    },
    startImportResultTimer(self) {
      function intervalFunc() {
        $.ajax({
          url: '/mgr/monthTicketBill/getImportBillResult.do',
          dataType: 'json',
          data: {},
          type: 'get',
          success: function (result) {
            if (result.status == 1) {
              self.importResult = result.data;
              if (!self.importResult || self.importResult.totalCount == self.importResult.processedCount) {
                clearInterval(getImportResultTimer);
              }
              self.uploadProgreeResult = '';
              self.percentage = 10;
            }
          }
        });
      }
      intervalFunc();
      var getImportResultTimer = setInterval(function () {
        intervalFunc();
      }, 1000);
    },
    downloadError() {
      var self = this;
      if (self.importResult.ossKey != '') {
        API.fetchGet('/authz/user/downloadBatchResult', {
          ossKey: self.importResult.ossKey
        }).then(
          res => {
            let data = res.data;
            window.location.href = data;
          },
          err => {}
        );
      } else {
        window.location.href = encodeURI(
          '/mgr/common/downloadNotDelete.do?fileName=' + self.importResult.errorFileName
        );
      }
    },
    downloadTmp() {
      var self = this;
      let params = {
        fileName: 'month_ticket_bill',
        fileType: 'xls'
      };
      $.ajax({
        url: '/mgr/importFlie/createExcelTmp.do',
        dataType: 'json',
        data: params,
        type: 'get',
        success: function (result) {
          var r = result;
          if (r && r.success) {
            self.showToast('下载成功', 1);
            window.location.href = encodeURI('/mgr/common/templateDownload.do?fileName=' + r.fileName);
          } else {
            self.showToast('下载失败', 2);
          }
        }
      }); //ajax end
    },
    // 记录进度
    recordProgress() {
      if (this.percentage >= 100) {
        clearInterval(this.uploadFileTimer);
        return;
      }
      this.percentage += 10;
    },
    sureImport() {
      var self = this;
      var formData = new FormData();
      formData.append('importFile', self.importFile.importFile);
      formData.append('im12portFile', 'self.importFile.importFile');
      if (!this.importFile.importFile) {
        self.showToast('请先选择文件', 1);
        return false;
      }
      var objtype = this.importFile.importFile.name
        .substring(this.importFile.importFile.name.lastIndexOf('.'))
        .toLowerCase();
      if (objtype != '.xls') {
        self.showToast('只支持xls格式文件', 1);
        return false;
      }
      self.uploadProgreeResult = 1;
      self.importResult = '';
      self.uploadFileTimer = setInterval(self.recordProgress(), 5);
      API.monthTicket.billImportBills(formData).then(
        res => {
          var data = res;
          if (res.status == 1) {
            clearInterval(self.uploadFileTimer);
            self.percentage = 100;
            self.importFile.importFile = '';
            self.fileName = '';
            setTimeout(function () {
              self.startImportResultTimer(self);
            }, 500);
          }
        },
        err => {}
      );
    },
    getFile(event) {
      this.importFile.importFile = event.target.files[0];
    },
    inviteCarCodeShowModal(row, modalName) {
      let self = this,
        params = {
          monthTicketBillId: row.id
        };
      self.inviteCarList = [];
      API.monthTicket.getInviteCarList(params).then(
        res => {
          let list = res.data;
          self.inviteCarList = list;
        },
        err => {}
      );
      this.toOpenModal(modalName);
    },
    deleteInviteCarCode(row) {
      let self = this,
        params = {
          id: row.id,
          monthTicketBillId: row.monthTicketBillId
        };

      self.showDialog('确认删除该邀请车牌?', '', function () {
        self.inviteCarList = [];
        API.monthTicket.deleteInviteCar(params).then(
          res => {
            let list = res.data;
            if (list) {
              self.inviteCarList = list;
              self.getList();
              self.showToast('删除成功', 1);
            } else {
              self.showToast('删除失败', 1);
            }
          },
          err => {}
        );
      });
    },
    // 批量续费
    renewBatch() {
      var self = this;
      self.startRenewBatchResultTimer(self);
      self.toOpenModal('renewBatchModal');
    },
    getRenewBatchFile(event) {
      this.renewBatchForm.renewBatchFile = event.target.files[0];
    },
    sureRenewBatch(event) {
      event.preventDefault();

      // 上传的文件
      var renewBatchFile = this.renewBatchForm.renewBatchFile;
      if (!renewBatchFile) {
        this.showToast('请先选择文件', 1);
        return false;
      }

      // 判断上传的文件格式是否为xls
      var renewBatchFileName = renewBatchFile.name.toLowerCase();
      var renewBatchFileType = renewBatchFileName.substring(renewBatchFileName.lastIndexOf('.'));
      if (renewBatchFileType != '.xls') {
        self.showToast('只支持xls格式文件', 1);
        return false;
      }

      var formData = new FormData();
      formData.append('renewFile', renewBatchFile);

      var self = this;
      API.monthTicket.renewBills(formData).then(
        res => {
          if (res.status == 1) {
            self.renewBatchForm.renewBatchFile = '';
            $('#renewBatchFileInput').val('');
            setTimeout(function () {
              self.startRenewBatchResultTimer(self);
            }, 1000);
          }
        },
        err => {}
      );
    },
    startRenewBatchResultTimer(self) {
      function intervalFunc() {
        $.ajax({
          url: '/mgr/monthTicketBill/getRenewBillsResult.do',
          dataType: 'json',
          data: {},
          type: 'get',
          success: function (result) {
            if (result.status == 1) {
              self.renewBatchResult = result.data;
              if (!self.renewBatchResult || self.renewBatchResult.totalCount == self.renewBatchResult.processedCount) {
                clearInterval(getRenewBatchResultTimer);
              }
            }
          }
        });
      }
      // 定时器
      intervalFunc();
      var getRenewBatchResultTimer = setInterval(function () {
        intervalFunc();
      }, 1000);
    },
    downloadError4RenewBatch() {
      var self = this;
      if (self.renewBatchResult.errorFileName != '') {
        window.location.href = encodeURI(
          '/mgr/common/downloadNotDelete.do?fileName=' + self.renewBatchResult.errorFileName
        );
      }
    },
    // 批量退费
    batchRefund() {
      var self = this;
      self.startBatchRefundResultTimer(self);
      self.toOpenModal('batchRefundModal');
    },
    getBatchRefundFile(event) {
      this.batchRefundForm.batchRefundFile = event.target.files[0];
    },
    sureBatchRefund(event) {
      event.preventDefault();

      // 上传的文件
      var batchRefundFile = this.batchRefundForm.batchRefundFile;
      if (!batchRefundFile) {
        this.showToast('请先选择文件', 1);
        return false;
      }

      // 判断上传的文件格式是否为xls
      var batchRefundFileName = batchRefundFile.name.toLowerCase();
      var batchRefundFileType = batchRefundFileName.substring(batchRefundFileName.lastIndexOf('.'));
      if (batchRefundFileType != '.xls') {
        self.showToast('只支持xls格式文件', 1);
        return false;
      }

      var formData = new FormData();
      formData.append('refundFile', batchRefundFile);
      var self = this;
      API.monthTicket.refundBills(formData).then(
        res => {
          if (res.status == 1) {
            self.batchRefundForm.batchRefundFile = '';
            $('#batchRefundFileInput').val('');
            setTimeout(function () {
              self.startBatchRefundResultTimer(self);
            }, 1000);
          }
        },
        err => {}
      );
    },
    startBatchRefundResultTimer(self) {
      function intervalFunc() {
        $.ajax({
          url: '/mgr/monthTicketBill/getBatchRefundResult.do',
          dataType: 'json',
          data: {},
          type: 'get',
          success: function (result) {
            if (result.status == 1) {
              self.batchRefundResult = result.data;
              if (
                !self.batchRefundResult ||
                self.batchRefundResult.totalCount == self.batchRefundResult.processedCount
              ) {
                clearInterval(getBatchRefundResultTimer);
              }
            }
          }
        });
      }
      // 定时器
      intervalFunc();
      var getBatchRefundResultTimer = setInterval(function () {
        intervalFunc();
      }, 1000);
    },
    downloadError4BatchRefund() {
      var self = this;
      if (self.batchRefundResult.errorFileName != '') {
        window.location.href = encodeURI(
          '/mgr/common/downloadNotDelete.do?fileName=' + self.batchRefundResult.errorFileName
        );
      }
    },
    //导出
    _export() {
      let self = this;
      let theadsArr = [];
      for (let i = 0; i < self.theadsInfo.length; i++) {
        if (self.theadsInfo[i].checked) {
          theadsArr.push(self.theadsInfo[i].prop);
        }
      }
      let params = {
        meterList: theadsArr.join(',')
      };

      params = $.extend({}, params, this.searchParams, this.otherParams);
      if(params.hasOwnProperty("query_carCode")){
        delete params.query_carCode
        let attribStr = this.searchList[0].value
        params[attribStr] = this.searchList[0].inputVal
      }
      if(params){
        for(let key in params){
          if(params.hasOwnProperty(key) && !params[key]){
            delete params[key]
          }
        }
      }
      this.toExportAsync('monthTicketBill/export', params);
    },
    startResyncMessageTimer() {
      let self = this;
      window.clearInterval(self.resyncMessageTimer);
      self.resyncMessageTimer = setInterval(() => {
        $.ajax({
          url: '/mgr/monthTicketBill/findResyncResult.do',
          dataType: 'json',
          data: {},
          type: 'post',
          success: function (result) {
            window.clearInterval(self.resyncMessageTimer);
            if (result.message == 'end') {
              if (result.data != '') {
                self.toOpenModal('billResyncResultModal');
                self.resyncMessage = result.data.split('。');
              }
              self.ifResync = false;
            } else {
              if (result.data != '') {
                self.toOpenModal('billResyncResultModal');
                self.resyncMessage = result.data.split('。');
                self.ifResync = true;
              }
            }
          }
        });
      }, 5000);
    },
    clsoeBillResyncResult(flag) {
      let self = this;
      if (flag) {
        self.closed('billResyncResultModal');
      }
      if (self.ifResync) {
        self.startResyncMessageTimer();
      }
      self.getList();
    },
    calculateTotalMoney2(value, billObj) {
      if (value) {
        let now1 = moment(value[0]);
        let now2 = moment(value[1]);
        let days = now2.diff(now1, 'day');
        billObj.openMonthNum = days + 1; //开通天数
        billObj.totalValue = (billObj.price * billObj.openMonthNum * billObj.dynamicCarportNumber) >> 0; //总价
      } else {
        billObj.openMonthNum = '';
        billObj.totalValue = '';
      }
    },

    // 自定义日期计算总金额
    calculateTotalMoney(value, billObj) {
      if (value) {
        var now1 = new Date(value[0]);
        var now2 = new Date(value[1]);
        var nowYear1 = now1.getFullYear();
        var nowYear2 = now2.getFullYear();
        var nowMonth1 = now1.getMonth() + 1;
        var nowMonth2 = now2.getMonth() + 1;
        var nowDay1 = now1.getDate();
        var nowDay2 = now2.getDate();
        var fullMonth1 = new Date(nowYear1, nowMonth1, 0).getDate();
        var fullMonth2 = new Date(nowYear2, nowMonth2, 0).getDate();
        //对一月到二月的续费进行特殊处理
        if (
          nowMonth1 == 1 &&
          (fullMonth1 == 30 || fullMonth1 == 31 || fullMonth1 == 29) &&
          nowMonth2 == 2 &&
          (nowDay2 == 28 || nowDay2 == 29)
        ) {
          billObj.openMonthNum = (nowYear2 - nowYear1) * 12 + 1;
        }
        // 计算自定义的开通或者续费的月份
        else if (nowDay1 == nowDay2 + 1) {
          //刚好是差一天算整n月
          billObj.openMonthNum = nowYear2 * 12 + nowMonth2 - (nowYear1 * 12 + nowMonth1);
        } else if (nowYear1 == nowYear2 && nowMonth1 == nowMonth2) {
          //同一个月计算
          billObj.openMonthNum = this.returnFloat((nowDay2 - nowDay1 + 1) / fullMonth2);
        } else if (nowDay1 < nowDay2 + 1) {
          var openMonthNum =
            nowYear2 * 12 + nowMonth2 - (nowYear1 * 12 + nowMonth1) + (nowDay2 - nowDay1 + 1) / fullMonth2;
          billObj.openMonthNum = this.returnFloat(openMonthNum);
        } else {
          var openMonthNum =
            nowYear2 * 12 + nowMonth2 - (nowYear1 * 12 + nowMonth1) - 1 + (nowDay2 - nowDay1 + 30) / 30;
          billObj.openMonthNum = this.returnFloat(openMonthNum);
        }
        billObj.totalValue = this.returnFloat(billObj.price * billObj.openMonthNum * billObj.dynamicCarportNumber);
      } else {
        billObj.totalValue = '';
        billObj.openMonthNum = '';
      }
    }
  }
};